package com.green_reading.mandolin;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import butterknife.ButterKnife;
import butterknife.BindView;

import com.green_reading.mandolin.SimpleService.ServerAPI;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChatActivity extends Activity {
    private final static String TAG = ChatActivity.class.getCanonicalName();
    private static final int REQUEST_VIDEO = 101;
    private static final int REQUEST_FILE_TRANSFORM = 102;
    //private Map<Integer, Map<String, String>> messages = new HashMap<Integer, Map<String, String>>();
    ArrayList<Map<String, Object>> messageList = new ArrayList<>();
    private DBManager dbManager;
    private String userName;
    private String peerName;
    private Integer userId;
    private Integer peerId;
    SimpleAdapter simpleAdapter;

    @BindView(R.id.chat_msg) EditText chat_msg;
    @BindView(R.id.chat_video) Button chat_video;
    @BindView(R.id.chat_send) Button chat_send;
    @BindView(R.id.chat_view) ListView chat_view;

    protected void toast(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_chat);
        ButterKnife.bind(this);
        dbManager = new DBManager(this);

        chat_send.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String content = chat_msg.getText().toString();
                if(content.equals("")) {
                    toast("message is empty!");
                    return;
                }
                Long create_time = Util.getDatetimeString();
                Long id = dbManager.addMessage(peerId, userId, content, 0, create_time);

                Map<String, Object> map = new HashMap<>();
                map.put("id", id);
                map.put("contacts_img", R.mipmap.ic_launcher);
                map.put("message_content", content);
                messageList.add(messageList.size(), map);
                simpleAdapter.notifyDataSetChanged();
            }
        });

        chat_video.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), SignupActivity.class);
                startActivityForResult(intent, REQUEST_VIDEO);
            }
        });

        Intent intent = getIntent();
        userName = intent.getStringExtra("userName");
        peerName = intent.getStringExtra("peerName");
        userId = intent.getIntExtra("userId", 0);
        peerId = intent.getIntExtra("peerId", 0);
        fillMessages();
    }

    private void getMessageList() {
        List<Map<String, String>> query_messages = dbManager.queryMessage(peerId, userId);
        Log.d(TAG, query_messages.toString());
        for(int i = 0; i < query_messages.size(); i++) {
            /*Map<String, String> message = new HashMap<String, String>();
            message.put("content", query_messages.get(i).get("content"));
            message.put("create_time", query_messages.get(i).get("create_time"));
            messages.put(i, message);*/

            Map<String, Object> map = new HashMap<>();
            map.put("id", query_messages.get(i).get("id"));
            map.put("contacts_img", R.mipmap.ic_launcher);
            map.put("message_content", query_messages.get(i).get("content"));
            messageList.add(i, map);
        }
    }
    private void fillMessages() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                getMessageList();
                simpleAdapter = new SimpleAdapter(
                        ChatActivity.this, messageList, R.layout.messages,
                        new String[] {"contacts_img", "message_content"},
                        new int[] {R.id.contacts_img, R.id.message_content});
                chat_view.setAdapter(simpleAdapter);

                chat_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                        //Log.d(TAG, position + ": " + messages.get(position).toString());
                        Builder builder=new Builder(ChatActivity.this);
                        builder.setTitle("Delete?");
                        builder.setMessage("Are you sure you want to delete?" + position);
                        builder.setNegativeButton("Cancel", null);
                        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                simpleAdapter.getItem(position);
                                dbManager.deleteMessageById(
                                        (Integer)messageList.get(position).get("id"));
                                chat_view.removeViewAt(position);
                                //simpleAdapter.notifyDataSetChanged();
                            }});
                        builder.show();
                    }
                });
            }
        });

    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    public void onDestroy() {
        super.onDestroy();
    }
}